<?php
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$auth = new WeChatAuth();

// 获取请求方法和数据
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'POST':
        if (isset($_GET['action'])) {
            switch ($_GET['action']) {
                case 'login':
                    // 微信小程序登录
                    if (!isset($input['code'])) {
                        Response::error('缺少code参数');
                    }
                    
                    $result = $auth->login($input['code']);
                    
                    if ($result['success']) {
                        Response::success($result['data'], '登录成功');
                    } else {
                        Response::error($result['message']);
                    }
                    break;
                    
                case 'update_profile':
                    // 更新用户信息
                    $user = $auth->getCurrentUser();
                    if (!$user) {
                        Response::authError('请先登录');
                    }
                    
                    error_log("Update profile request: " . json_encode($input));
                    error_log("Current user: " . json_encode($user));
                    
                    $db = new Database();
                    $updateData = [];
                    
                    // 处理微信用户信息
                    if (isset($input['userInfo'])) {
                        $userInfo = $input['userInfo'];
                        if (isset($userInfo['nickName'])) $updateData['nickname'] = $userInfo['nickName'];
                        if (isset($userInfo['avatarUrl'])) $updateData['avatar'] = $userInfo['avatarUrl'];
                    }
                    
                    // 处理其他用户信息
                    if (isset($input['nickname'])) $updateData['nickname'] = trim($input['nickname']);
                    if (isset($input['avatar'])) $updateData['avatar'] = trim($input['avatar']);
                    if (isset($input['phone'])) {
                        // 验证手机号格式
                        $phone = trim($input['phone']);
                        if (!empty($phone) && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
                            Response::error('手机号格式不正确');
                        }
                        $updateData['phone'] = $phone;
                    }
                    if (isset($input['real_name'])) $updateData['real_name'] = trim($input['real_name']);
                    if (isset($input['id_card'])) $updateData['id_card'] = trim($input['id_card']);
                    if (isset($input['student_id'])) $updateData['student_id'] = trim($input['student_id']);
                    if (isset($input['department'])) $updateData['department'] = trim($input['department']);
                    if (isset($input['grade'])) $updateData['grade'] = trim($input['grade']);
                    
                    error_log("Update data prepared: " . json_encode($updateData));
                    
                    if (!empty($updateData)) {
                        $updateData['updated_at'] = date('Y-m-d H:i:s');
                        $result = $db->update('users', $updateData, 'id = :user_id', ['user_id' => $user['id']]);
                        
                        if (!$result) {
                            error_log("Update failed for user ID: " . $user['id']);
                            Response::error('更新失败，请重试');
                        }
                        
                        error_log("Update result: " . ($result ? 'success' : 'failed'));
                    } else {
                        error_log("No data to update");
                    }
                    
                    // 返回更新后的用户信息
                    $updatedUser = $db->fetchOne("SELECT * FROM users WHERE id = ?", [$user['id']]);
                    error_log("Updated user data: " . json_encode($updatedUser));
                    Response::success($updatedUser, '信息更新成功');
                    break;
                    
                case 'toggle_subscribe':
                    // 切换订阅消息开关
                    $user = $auth->getCurrentUser();
                    if (!$user) {
                        Response::authError('请先登录');
                    }
                    
                    $subscribe = isset($input['subscribe']) ? (int)$input['subscribe'] : 1;
                    
                    $db = new Database();
                    $db->update('users', ['subscribe_message' => $subscribe], 'id = ?', [$user['id']]);
                    
                    Response::success(['subscribe_message' => $subscribe], '设置更新成功');
                    break;
                    
                case 'decrypt_phone':
                    // 解密微信手机号
                    $user = $auth->getCurrentUser();
                    if (!$user) {
                        Response::authError('请先登录');
                    }
                    
                    if (!isset($input['encryptedData']) || !isset($input['iv'])) {
                        Response::error('缺少加密数据');
                    }
                    
                    // 这里需要实现微信数据解密
                    // 由于需要session_key，建议在登录时保存，或者重新获取
                    try {
                        $phoneInfo = $auth->decryptData($input['encryptedData'], $input['iv'], $user['openid']);
                        
                        if ($phoneInfo && isset($phoneInfo['phoneNumber'])) {
                            // 更新用户手机号
                            $db = new Database();
                            $db->update('users', [
                                'phone' => $phoneInfo['phoneNumber'],
                                'updated_at' => date('Y-m-d H:i:s')
                            ], 'id = ?', [$user['id']]);
                            
                            Response::success([
                                'phoneNumber' => $phoneInfo['phoneNumber']
                            ], '获取手机号成功');
                        } else {
                            Response::error('解密手机号失败');
                        }
                    } catch (Exception $e) {
                        Response::error('解密失败：' . $e->getMessage());
                    }
                    break;
                    
                case 'save_common_visitor':
                    // 保存常用观众信息
                    $user = $auth->getCurrentUser();
                    if (!$user) {
                        Response::authError('请先登录');
                    }
                    
                    if (!isset($input['name']) || !isset($input['id_number'])) {
                        Response::error('缺少必要参数');
                    }
                    
                    $db = new Database();
                    
                    // 检查是否已存在相同的常用观众
                    $existing = $db->fetchOne("
                        SELECT id FROM common_visitors 
                        WHERE user_id = ? AND id_number = ?
                    ", [$user['id'], $input['id_number']]);
                    
                    if ($existing) {
                        Response::error('该观众信息已存在');
                    }
                    
                    $visitorId = $db->insert('common_visitors', [
                        'user_id' => $user['id'],
                        'name' => $input['name'],
                        'id_type' => $input['id_type'] ?? '身份证',
                        'id_number' => $input['id_number'],
                        'phone' => $input['phone'] ?? '',
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                    
                    if ($visitorId) {
                        Response::success(['id' => $visitorId], '保存成功');
                    } else {
                        Response::error('保存失败');
                    }
                    break;
                    
                default:
                    Response::error('无效的操作');
            }
        } else {
            Response::error('缺少action参数');
        }
        break;
        
    case 'GET':
        if (isset($_GET['action'])) {
            switch ($_GET['action']) {
                case 'profile':
                    // 获取用户信息
                    $user = $auth->getCurrentUser();
                    if (!$user) {
                        Response::authError('请先登录');
                    }
                    
                    Response::success($user, '获取成功');
                    break;
                    
                case 'common_visitors':
                    // 获取常用观众信息
                    $user = $auth->getCurrentUser();
                    if (!$user) {
                        Response::authError('请先登录');
                    }
                    
                    $db = new Database();
                    $visitors = $db->fetchAll("
                        SELECT * FROM common_visitors 
                        WHERE user_id = ? 
                        ORDER BY created_at DESC
                    ", [$user['id']]);
                    
                    Response::success($visitors, '获取成功');
                    break;
                    
                default:
                    Response::error('无效的操作');
            }
        } else {
            Response::error('缺少action参数');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>